package luo;
import java.sql.*;
public class DataBase {
	/*
	 * 数据库的基本类，进行数据库操作时候都应该加载
	 */
	private String driverName;
	private String dbURL;
	private String userName;
	private String userPwd;
	private Connection dbConnect;	
	public DataBase(){
		//数据库加载
		  this.driverName = "com.microsoft.sqlserver.jdbc.SQLServerDriver";   //加载jdbc驱动 
		  this.dbURL = "jdbc:sqlserver://localhost:1433; DatabaseName=dbhomework";   //创建连接t  
		  this.userName = "sa";   //账号
		  this.userPwd = "123";   //密码  
		try{
			Class.forName(driverName);
			dbConnect=DriverManager.getConnection(dbURL, userName, userPwd);
		}catch(Exception e){
			System.out.println("数据库加载不成功！");
		}
	}
	
	//显示查询结果
	public void display(ResultSet resultSet) throws SQLException{
		ResultSetMetaData reMetaData=resultSet.getMetaData();	
		for(int i=1;i<=reMetaData.getColumnCount();i++)
		   System.out.printf("%-30s\t",reMetaData.getColumnName(i));
		   System.out.println();
		   while(resultSet.next()){
			   for(int i=1;i<=reMetaData.getColumnCount();i++)      	  
				   System.out.printf("%-30s\t",resultSet.getObject(i));
			   System.out.println();        	  				
		   }
		}
	/*
	 *查询，需要SQL语句
	 */
	public ResultSet query(String query_sta) throws SQLException{
		try{
			Statement statement=this.dbConnect.createStatement();	
			ResultSet resultSet=statement.executeQuery(query_sta);
			return resultSet;
		}catch(SQLException e){
			e.printStackTrace(); 
		}
		return null;		
	}
	/*
	 * 插入，删除，更新数据
	 * 需要SQL语句
	 */
	public boolean update(String query_sta) throws SQLException{
		try{
			Statement statement=this.dbConnect.createStatement();	
			int afffect_rows=statement.executeUpdate(query_sta);
			if(afffect_rows>0){
				return true;
			}else{
				return false;
			}			
		}catch(SQLException e){
			e.printStackTrace(); 
		}
		return false;				
	}
	
	//关闭数据库
	public void close_connect(){
		try{
			this.dbConnect.close();
		}catch(SQLException e){
			e.printStackTrace(); 
		}
	}
	//用户验证
	public boolean user_validation(String email,String password){
		 try {
			 ResultSet result=this.query("select email,password from user_infor where email="+"'"+email+"' and password="+"'"+password+"'");
			 if(result.next()){
				 return true;
			 }else{
				 return false;
			 }
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			 return false;
		}
	}

	
}
